<template>
  <div>
    <AxiomSearchToolbar :fields="searchFields" @search="handleSearch" />
    <AxiomToolbar>
      <AxiomButton type="primary" icon="Plus" @click="handleCreate">新增用户</AxiomButton>
      <AxiomButton
        type="danger"
        icon="Delete"
        :disabled="!selectedRows.length"
        @click="handleBatchDelete"
      >
        批量删除
      </AxiomButton>
    </AxiomToolbar>
    <AxiomDataTable
      ref="dataTableRef"
      :title="title"
      :columns="columns"
      :data="userList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <template #status="{ row }">
        <AxiomSwitch
          :model-value="row.status === 1"
          :disabled="row.username === 'admin'"
          @change="(newState) => handleStatusChange(row, newState)"
        />
      </template>
      <template #action="{ row }">
        <AxiomButton type="primary" text icon="Edit" @click="handleEdit(row)">编辑</AxiomButton>
        <AxiomButton type="primary" text icon="Setting" @click="handleAssignRole(row)">分配角色</AxiomButton>
        <AxiomButton type="danger" text icon="Delete" @click="handleDelete(row)">删除</AxiomButton>
      </template>
    </AxiomDataTable>

    <UserFormDialog
      :visible="formDialogVisible"
      :initial-data="currentUserData"
      :mode="dialogMode"
      @close="handleFormDialogClose"
      @success="handleFormDialogSuccess"
    />

    <AssignRoleDialog
      :visible="assignDialogVisible"
      :user-data="currentUserData"
      @close="handleAssignDialogClose"
      @success="handleAssignDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from 'vue';
import {
  AxiomButton,
  AxiomDataTable,
  AxiomSearchToolbar,
  AxiomToolbar,
  AxiomTag,
  AxiomSwitch,
} from 'axiom-view';
import {
  getUserList,
  deleteUser,
  enableUser,
  disableUser,
  batchDeleteUsers
} from '@/api/system/user';
import UserFormDialog from './UserFormDialog.vue';
import AssignRoleDialog from './AssignRoleDialog.vue';

const { notification, useConfirm } = inject('axiom-utils');
const { show: showConfirm } = useConfirm;

const title = ref('用户管理');
const loading = ref(false);
const userList = ref([]);
const selectedRows = ref([]);
const dataTableRef = ref(null);

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});
const searchQuery = reactive({});

const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 },
];

const searchFields = ref([
  { model: 'username', label: '用户名', type: 'input', placeholder: '请输入用户名' },
  { model: 'email', label: '邮箱', type: 'input', placeholder: '请输入邮箱' },
  { model: 'status', label: '状态', type: 'select', options: statusOptions },
]);

const columns = ref([
  { type: 'selection', width: 55 },
  { prop: 'username', label: '用户名', width: 150 },
  { prop: 'nickname', label: '昵称', width: 150 },
  { prop: 'email', label: '邮箱' },
  { prop: 'status', label: '状态', width: 100, slot: 'status' },
  { prop: 'create_time', label: '创建时间', width: 180 },
  { prop: 'action', label: '操作', width: 220, slot: 'action' },
]);

// Dialog states
const formDialogVisible = ref(false);
const dialogMode = ref('add');
const currentUserData = ref(null);
const assignDialogVisible = ref(false);

const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      ...searchQuery,
    };
    const res = await getUserList(params);
    if (res.success && res.data) {
      userList.value = res.data.items.map(user => ({
        ...user,
        // 确保 status 始终是数字类型
        status: Number(user.status)
      }));
      pagination.total = res.data.total;
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (newPage) => {
  pagination.currentPage = newPage;
  fetchData();
};

const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize;
  pagination.currentPage = 1;
  fetchData();
};

const handleSearch = (query) => {
  Object.keys(searchQuery).forEach(key => delete searchQuery[key]);
  Object.assign(searchQuery, query);
  pagination.currentPage = 1;
  fetchData();
};

const handleCreate = () => {
  dialogMode.value = 'add';
  currentUserData.value = {};
  formDialogVisible.value = true;
};

const handleEdit = (row) => {
  if (row.username === 'admin') {
    notification.warning({ title: '操作受限', message: '不允许编辑超级管理员用户。' });
    return;
  }
  dialogMode.value = 'edit';
  currentUserData.value = { ...row };
  formDialogVisible.value = true;
};

const handleAssignRole = (row) => {
  if (row.username === 'admin') {
    notification.warning({ title: '操作受限', message: '不允许为超级管理员分配角色。' });
    return;
  }
  currentUserData.value = { ...row };
  assignDialogVisible.value = true;
};

const handleDelete = async (row) => {
  if (row.username === 'admin') {
    notification.warning({ title: '操作受限', message: '不允许删除超级管理员用户。' });
    return;
  }
  await showConfirm({
    title: '确认删除',
    content: `您确定要删除用户【${row.username}】吗？`,
    type: 'error',
    onConfirm: async () => {
      await deleteUser(row.id);
      notification.success({ title: '成功', message: '删除成功' });
      fetchData(); // Refresh data
    }
  });
};

const handleBatchDelete = async () => {
  if (!selectedRows.value.length) {
    notification.warning({ title: '提示', message: '请至少选择一个用户' });
    return;
  }

  // 检查是否包含 admin 用户
  const containsAdmin = selectedRows.value.some(row => row.username === 'admin');
  if (containsAdmin) {
    notification.error({ title: '操作失败', message: '选中的用户中包含超级管理员，无法删除。' });
    return;
  }

  await showConfirm({
    title: '确认批量删除',
    content: `您确定要删除选中的 ${selectedRows.value.length} 个用户吗？此操作不可逆。`,
    type: 'error',
    onConfirm: async () => {
      const ids = selectedRows.value.map(row => row.id);
      await batchDeleteUsers(ids);
      notification.success({ title: '成功', message: '批量删除成功' });
      if (dataTableRef.value) {
        dataTableRef.value.clearSelection();
      }
      fetchData();
    }
  });
};

const handleStatusChange = async (row, newState) => {
  const originalStatus = row.status;
  // 立即在UI上更新状态以获得更好的用户体验
  row.status = newState ? 1 : 0;
  
  try {
    const action = newState ? enableUser : disableUser;
    await action(row.id);
    notification.success({ title: '成功', message: '状态更新成功' });
  } catch (error) {
    // 如果API调用失败，将状态恢复到原始状态
    row.status = originalStatus;
    console.error('更新用户状态失败:', error);
    // 全局的 apiClient 会显示错误通知
  }
};

const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// Form Dialog methods
const handleFormDialogClose = () => {
  formDialogVisible.value = false;
  currentUserData.value = null;
};

const handleFormDialogSuccess = () => {
  fetchData();
  handleFormDialogClose();
};

// Assign Role Dialog methods
const handleAssignDialogClose = () => {
  assignDialogVisible.value = false;
  currentUserData.value = null;
};

const handleAssignDialogSuccess = () => {
  fetchData();
  handleAssignDialogClose();
};

onMounted(() => {
  fetchData();
});
</script> 